//
//  UpdateHeadPhotoViewController.m
//  Cycling
//
//  Created by cjg.mini on 2023/3/29.
//

#import "UpdateHeadPhotoViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "QBImagePickerController.h"
#import "MineRequest.h"

@interface UpdateHeadPhotoViewController ()<QBImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic, strong) UIView *naviBarView;

@end

@implementation UpdateHeadPhotoViewController

- (UIView *)naviBarView {
    if (!_naviBarView) {
        _naviBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, NavigationBarHeight)];
        _naviBarView.backgroundColor = COLOR_WHITE;
        UILabel *titleLB = [[UILabel alloc] initWithFrame:CGRectMake(MARGIN_MAX, SafeAreaTopHeight, SCREEN_W-MARGIN_MAX*2, 44)];
        titleLB.text = self.carID.length == 0 ? CycLocalizedString(@"Profile", "头像") : @"车辆图片";
        titleLB.textAlignment = NSTextAlignmentCenter;
        titleLB.textColor = rgbHex(0x222222, 1.0);
        titleLB.font = FONT_PRIMARY_TITLE;
        [_naviBarView addSubview:titleLB];
    }
    return _naviBarView;
}

- (void)clickImageView:(UITapGestureRecognizer *)sender {
    UIAlertController *alertPhoto = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    alertPhoto.popoverPresentationController.sourceView = self.view;
    alertPhoto.popoverPresentationController.sourceRect = CGRectMake(0,SCREEN_W/2,SCREEN_W,SCREEN_H);

    [self presentViewController:alertPhoto animated:YES completion:nil];
//        __weak typeof(self)weakSelf = self;
    
    UIAlertAction *camaraSeleect = [UIAlertAction actionWithTitle:CycLocalizedString(@"Camera", @"拍照") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhotos];
    }];
    [alertPhoto addAction:camaraSeleect];
    
    UIAlertAction *pictureSelect = [UIAlertAction actionWithTitle:CycLocalizedString(@"Gallery", @"从手机相册选取") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectPhoto];
    }];
    [alertPhoto addAction:pictureSelect];
    
    UIAlertAction *alertCanle = [UIAlertAction actionWithTitle:CycLocalizedString(@"Cancel", @"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertPhoto addAction:alertCanle];

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:NO animated:NO];

    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    // Do any additional setup after loading the view from its nib.
    if(self.carID.length == 0){
        self.imageView.layer.cornerRadius = SCREEN_W/2;
        self.imageView.layer.masksToBounds = YES;
    }
    if(self.carID.length == 0){
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:self.model.userinfo.avatar] placeholderImage:[UIImage imageNamed:@"icon_mine_head"]];
    }else {
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:self.model.equipment.image] placeholderImage:[UIImage imageNamed:@"icon_mine_car_im"]];
    }
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickImageView:)];
    [self.imageView addGestureRecognizer:tap];
    [self.view addSubview:self.naviBarView];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(20, SafeAreaTopHeight, 70, 40);
    [btn setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateHighlighted];
    
    [btn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.naviBarView addSubview:btn];


}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

//去拍照
- (void)takePhotos {
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
//        DLog(@"%@",granted ? @"相机准许":@"相机不准许");
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!granted) {
                [self nounShow:0];
            } else {
                UIImagePickerController *imgController = [[UIImagePickerController alloc] init];
                imgController.sourceType = UIImagePickerControllerSourceTypeCamera;
                imgController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
                NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
                [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
                imgController.mediaTypes = mediaTypes;
                imgController.delegate = self;
                imgController.allowsEditing = YES;
                [self presentViewController:imgController
                                   animated:YES
                                 completion:^(void) {
//                    DLog(@"Picker View Controller is presented");
                }];
            }
        });
    }];
}
//去选照片
- (void)selectPhoto {
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (status != PHAuthorizationStatusAuthorized) {
                [self nounShow:1];
            } else {
                UIImagePickerController *imgController = [[UIImagePickerController alloc] init];
                imgController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
                [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
                imgController.mediaTypes = mediaTypes;
                imgController.delegate = self;
                imgController.allowsEditing = YES;
                [self presentViewController:imgController
                                   animated:YES
                                 completion:^(void) {
                }];
            }
        });
    }];
}

#pragma mark - UIImagePicker
- (void)nounShow:(NSInteger)type {
    NSString *message;
    if (type == 0) {
        message = CycLocalizedString(@"Please go to Settings ->Privacy ->Camera Authorization Application for photo permissions", @"请前往设置->隐私->相机授权应用拍照权限");
    } else {
        message = CycLocalizedString(@"Please go to Settings ->Privacy ->Photo Authorization Application for photo permissions", @"请前往设置->隐私->照片授权应用拍照权限");
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:CycLocalizedString(@"Note", @"提示") message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * sureAction = [UIAlertAction actionWithTitle:CycLocalizedString(@"Confirm", @"确认") style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
    }];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:true completion:nil];
}
#pragma mark - UIImagePicker Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *portraitImg = [info objectForKey:UIImagePickerControllerEditedImage];
    [self dismissViewControllerAnimated:YES completion:nil];
    if (portraitImg != nil) {

        self.imageView.image = portraitImg;
        NSData *file = UIImageJPEGRepresentation(portraitImg, 1);
        if(self.carID.length){
            [MineRequest uploadImageWithFile:file type:nil result:^(NSDictionary * _Nonnull ret) {
                if(ret){
                    [MineRequest uploadCarImageWithFile:ret[@"fullurl"] carId:self.carID result:^(BOOL ret) {
                        if (ret) {
                            [self showHudTipStr:CycLocalizedString(@"Image change success", @"图片设置成功")];
                            if(self.changedBlock) {
                                self.changedBlock();
                            }
                        }else {
                            [self showHudTipStr:CycLocalizedString(@"Image change fail", @"图片设置失败")];
                        }
                    }];

                }else {
                    [self showHudTipStr:CycLocalizedString(@"Image upload fail", @"图片上传失败")];
                }
            }];
        }else {
            [MineRequest uploadavatarWithFile:file type:nil result:^(NSDictionary * _Nonnull ret) {
                if (ret) {
                    [self showHudTipStr:CycLocalizedString(@"Photo change success", @"头像设置成功")];
                    if(self.changedBlock) {
                        self.changedBlock();
                    }
                }else {
                    [self showHudTipStr: CycLocalizedString(@"Photo change fail", @"头像设置失败")];
                }
            }];
        }
    }


}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - QBImagePickerControllerDelegate
- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAsset:(PHAsset *)mPhAsset {
    [[PHImageManager defaultManager] requestImageForAsset:mPhAsset
                                               targetSize:CGSizeMake(mPhAsset.pixelWidth, mPhAsset.pixelHeight)
                                              contentMode:PHImageContentModeDefault
                                                  options:nil
                                            resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {

    }];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
